package com.agileai.em.module.expreimbursement.handler;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.em.common.ProcessHelper;
import com.agileai.em.cxmodule.EmExpReimbursementManage;
import com.agileai.em.wsproxy.BizAttribute;
import com.agileai.em.wsproxy.HandleWorkItem;
import com.agileai.em.wsproxy.LaunchWorkItem;
import com.agileai.em.wsproxy.ProcessService;
import com.agileai.em.wsproxy.SubmitWorkItem;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class MobileExpreimbursementHandler extends SimpleHandler{
	private static String UNSUBMITTED = "UNSUBMITTED";
	private static String AUDITING = "AUDITING";
	private static String PAID = "PAID";
	private static String CANCEL = "CANCEL";
	public static final String PROCESS_CODE = "Expreimbursement";
	private static int pageSize = 20;
	private static String reload="reload";
	private static String refresh="refresh";
	public MobileExpreimbursementHandler(){
		super();
	}
	@PageAction
	public ViewRenderer findExpreimbursementList(DataParam param){
		String responseText = FAIL;
		try {
			EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
			User user = (User) this.getUser();
			param.put("ER_PERSON",user.getUserId());
			List<DataRow> records = emExpReimbursementManage.findRecords(param);
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<records.size();i++){
				JSONObject jsonObject1 = new JSONObject();
				DataRow row = records.get(i);
				String ID = row.getString("ER_ID");
				String TITLE = row.getString("ER_TITLE");
				String NAME = row.getString("ER_PERSON_NAME");
				Date erDate = (Date) row.get("ER_DATE");
				String DATE = DateUtil.getDateByType(DateUtil.YYMMDD_SLANTING, erDate);
				String STATE = row.getString("ER_STATE");
				String STATETEXT = row.getString("ER_STATE_TEXT");
				jsonObject1.put("id", ID);
				jsonObject1.put("title", TITLE);
				jsonObject1.put("name", NAME);
				jsonObject1.put("date", DATE);
				jsonObject1.put("state", STATE);
				jsonObject1.put("stateText", STATETEXT);
				jsonArray.put(jsonObject1);
			}
			jsonObject.put("expreList", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer retrieveExpreimbursementDetail(DataParam param){
		String responseText = FAIL;
		try {
			EmExpReimbursementManage emExpReimbursementManage = this.lookupService(EmExpReimbursementManage.class);
			User user = (User) this.getUser();
			param.put("ER_PERSON",user.getUserId());
			String ID = param.getString("ID");
			param.put("ER_ID",ID);
			DataRow record = emExpReimbursementManage.getRecord(param);
			JSONObject jsonObject = new JSONObject();
			String id = record.getString("ER_ID");
			String title = record.getString("ER_TITLE");
			String name = record.getString("ER_PERSON_NAME");
			Date erDate = (Date) record.get("ER_DATE");
			String date = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_SLANTING, erDate);
			BigDecimal money = (BigDecimal) record.get("ER_MONEY");
			String style = record.getString("ER_STYLE");
			String remark = record.getString("ER_REMARKS");
			if(StringUtil.isNullOrEmpty(remark)){
				remark = "无";
			}
			String state = record.getString("ER_STATE");
			String stateText = record.getString("ER_STATE_TEXT");
			jsonObject.put("id", id);
			jsonObject.put("title", title);
			jsonObject.put("name", name);
			jsonObject.put("date", date);
			jsonObject.put("money", money);
			jsonObject.put("style", style);
			jsonObject.put("desc", remark);
			jsonObject.put("state", state);
			jsonObject.put("stateText", stateText);
			List<DataRow> records = emExpReimbursementManage.findApproveOpinionRecords(param);
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<records.size();i++){
				JSONObject jsonObject1 = new JSONObject();
				DataRow row = records.get(i);
				jsonObject1.put("appName", row.getString("EXP_APP_PERSON_NAME"));
				jsonObject1.put("appResult", row.getString("EXP_APP_RESULT_NAME"));
				jsonObject1.put("appDate", row.get("EXP_APP_TIME"));
				String appOpinion = row.getString("EXP_APP_OPINION");
				if(StringUtil.isNullOrEmpty(appOpinion)){
					appOpinion = "无";
				}
				jsonObject1.put("appOpinion",appOpinion);
				jsonArray.put(jsonObject1);
			}
			jsonObject.put("appList", jsonArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer createExpreimbursementRecord(DataParam param){
		String responseText = FAIL;
		try {
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			User user = (User) this.getUser();
			String resquest = getInputString();
			JSONObject jsonObject = new JSONObject(resquest);			
			String title = jsonObject.getString("title");
			String style = jsonObject.getString("style");
			String strDate = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
			Date date = DateUtil.getDate(strDate);
			Integer money = (Integer) jsonObject.get("money");
			String remark = jsonObject.getString("desc");
			String state = UNSUBMITTED;
			DataParam createParam = new DataParam("ER_ID",null,"ER_TITLE",title,"ER_PERSON",user.getUserId(),"ER_DATE",date,
					"ER_MONEY",money,"ER_STYLE",style,"ER_REMARKS",remark,"ER_STATE",state);
			mobileManage.createRecord(createParam);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer editExpreimbursementRecord(DataParam param){
		String responseText = FAIL;
		try {
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			User user = (User) this.getUser();
			String id = param.getString("ID");
			String resquestJson = getInputString();
			JSONObject jsonObject = new JSONObject(resquestJson);			
			String title = jsonObject.getString("title");
			String style = jsonObject.getString("style");
			String strMoney = jsonObject.getString("money");
			BigDecimal money = new BigDecimal(strMoney);
			String strDate = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
			Date date = DateUtil.getDate(strDate);
			String state = UNSUBMITTED;
			String remark = jsonObject.getString("desc");
			DataParam updateParam = new DataParam("ER_ID",id,"ER_TITLE",title,"ER_PERSON",user.getUserId(),"ER_DATE",date,
					"ER_MONEY",money,"ER_STYLE",style,"ER_REMARKS",remark,"ER_STATE",state);
			mobileManage.updateRecord(updateParam);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer submitExpreimbursementRecord(DataParam param){
		String responseText = FAIL;
		try {
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			String ER_ID = param.getString("ID");
			String ER_STATE = AUDITING; 
			param.put("ER_ID", ER_ID,"ER_STATE",ER_STATE);
			mobileManage.changeStateRecord(param);
			
			DataRow row = mobileManage.getRecord(param);
			User user = (User) this.getUser();
			List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
	   		BizAttribute bizAttribute = new BizAttribute();
	   		bizAttribute.setCode("userId");
	   		bizAttribute.setValue(user.getUserId());
	   		attributeList.add(bizAttribute);
	   		String bizRecordId = ER_ID;
	   		if(StringUtil.isNullOrEmpty(bizRecordId)){
	   			bizRecordId = KeyGenerator.instance().genKey();
	   		}
	   		ProcessHelper processHelper = ProcessHelper.instance();
	   		ProcessService processService = processHelper.getBPMService();
	   		String processId = processService.getCurrentProcessId(PROCESS_CODE);
	   		String title = row.getString("ER_TITLE");
	   		LaunchWorkItem launchWorkItem = processHelper.createLaunchWorkItem(processId);
	   		launchWorkItem.getAttributeList().addAll(attributeList);
	   		launchWorkItem.setTitle(title);
	   		launchWorkItem.setBizRecordId(bizRecordId);
	   		launchWorkItem.setUserCode(user.getUserCode());
	   		param.put("SKIP_FIRST_NODE", "true");
	   		boolean skipFirstNode = "true".equals(param.get("SKIP_FIRST_NODE"));
	   		processService.launchProcess(launchWorkItem,skipFirstNode);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer deleteExpreimbursementRecord(DataParam param){
		String responseText = FAIL;
		try {
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			String ER_ID = param.getString("ID");
			param.put("ER_ID", ER_ID);
			mobileManage.deletRecord(param);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer approveTask(DataParam param){
		String responseText = FAIL;
		try {
			String resquest = getInputString();
			JSONObject jsonObject = new JSONObject(resquest);
			User user = (User) getUser();
			DataParam queryParam = new DataParam();
			queryParam.put("EXP_APP_ID",KeyGenerator.instance().genKey());
			queryParam.put("ER_ID",jsonObject.get("id"));
			queryParam.put("EXP_APP_PERSON",user.getUserId());
			queryParam.put("EXP_APP_OPINION",jsonObject.get("opinionContent"));
			queryParam.put("EXP_APP_RESULT",jsonObject.get("opinion"));
			queryParam.put("EXP_APP_TIME",new Date());
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			mobileManage.createApproveRecord(queryParam);
			
			ProcessHelper processHelper = ProcessHelper.instance();
			BizAttribute bizAttribute = new BizAttribute();
			bizAttribute.setCode("AppoperType");
			bizAttribute.setValue(jsonObject.getString("opinion"));
			BizAttribute bizAttribute1 = new BizAttribute();
			bizAttribute1.setCode("totalMoney");
			String money = String.valueOf(jsonObject.get("money"));
			bizAttribute1.setValue(money);
			List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
			attributeList.add(bizAttribute);
			attributeList.add(bizAttribute1);
			ProcessService bpmService = ProcessHelper.instance().getBPMService();
			String mobileBizUrl = (String) jsonObject.get("bizUrl");
			String[] flowInfoArray = mobileBizUrl.split("/");
			String processId = flowInfoArray[2];
			String processInstId = flowInfoArray[3];
			String activityCode = flowInfoArray[4];
			SubmitWorkItem processWorkItem = processHelper.createSubmitWorkItem(processId, processInstId, activityCode);
			if(StringUtil.isNullOrEmpty(attributeList.get(0).getCode())){
				attributeList = processWorkItem.getAttributeList();
			}
			processWorkItem.setUserCode(user.getUserCode());
			processWorkItem.getAttributeList().addAll(attributeList);
			bpmService.submitProcess(processWorkItem);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer submitTask(DataParam param){
		String responseText = FAIL;
		try {
			String resquest = getInputString();
			JSONObject jsonObject = new JSONObject(resquest);
			User user = (User) getUser();
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			String id = param.getString("ID");
			String title = jsonObject.getString("title");
			String style = jsonObject.getString("style");
			String strMoney = jsonObject.getString("money");
			BigDecimal money = new BigDecimal(strMoney);
			String strDate = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
			Date date = DateUtil.getDate(strDate);
			String state = AUDITING;
			String remark = jsonObject.getString("desc");
			DataParam updateParam = new DataParam("ER_ID",id,"ER_TITLE",title,"ER_PERSON",user.getUserId(),"ER_DATE",date,
					"ER_MONEY",money,"ER_STYLE",style,"ER_REMARKS",remark,"ER_STATE",state);
			mobileManage.updateRecord(updateParam);
			
			List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
			String mobileBizUrl = (String) param.get("bizUrl");
			String[] flowInfoArray = mobileBizUrl.split("/");
			String processId = flowInfoArray[2];
			String processInstId = flowInfoArray[3];
			String activityCode = flowInfoArray[4];
			
			ProcessHelper processHelper = ProcessHelper.instance();
			ProcessService bpmService = processHelper.getBPMService();
			SubmitWorkItem processWorkItem = processHelper.createSubmitWorkItem(processId, processInstId, activityCode);
			attributeList = processWorkItem.getAttributeList();
			processWorkItem.setUserCode(user.getUserCode());
			processWorkItem.getAttributeList().addAll(attributeList);
			bpmService.submitProcess(processWorkItem);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	@PageAction
	public ViewRenderer cancelTask(DataParam param){
		String responseText = FAIL;
		try {
			String resquest = getInputString();
			JSONObject jsonObject = new JSONObject(resquest);
			User user = (User) getUser();
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			String id = param.getString("ID");
			String title = jsonObject.getString("title");
			String style = jsonObject.getString("style");
			String strMoney = jsonObject.getString("money");
			BigDecimal money = new BigDecimal(strMoney);
			String strDate = DateUtil.getDateByType(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
			Date date = DateUtil.getDate(strDate);
			String state = CANCEL;
			String remark = jsonObject.getString("desc");
			DataParam updateParam = new DataParam("ER_ID",id,"ER_TITLE",title,"ER_PERSON",user.getUserId(),"ER_DATE",date,
					"ER_MONEY",money,"ER_STYLE",style,"ER_REMARKS",remark,"ER_STATE",state);
			mobileManage.updateRecord(updateParam);
			
			ProcessHelper processHelper = ProcessHelper.instance();
			ProcessService processService = processHelper.getBPMService();
			String mobileBizUrl = param.getString("bizUrl");
			String[] flowInfoArray = mobileBizUrl.split("/");
			String processId = flowInfoArray[2];
			String processInstId = flowInfoArray[3];
			
			HandleWorkItem handleWorkItem = new HandleWorkItem();
			handleWorkItem.setProcessId(processId);
			handleWorkItem.setProcessInstanceId(processInstId);
			handleWorkItem.setUserCode(user.getUserCode());
			processService.terminateProcess(handleWorkItem);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer cashTask(DataParam param){
		String responseText = FAIL;
		try {
			String resquest = getInputString();
			JSONObject jsonObject = new JSONObject(resquest);	
			User user = (User) getUser();
			DataParam newParam = new DataParam();
			newParam.put("ER_ID",jsonObject.get("id"));
			newParam.put("ER_STATE", "PAID");
			EmExpReimbursementManage mobileManage = this.lookupService(EmExpReimbursementManage.class);
			mobileManage.changeStateRecord(newParam);
			List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
			BizAttribute bizAttribute = new BizAttribute();
	   		bizAttribute.setCode("userId");
	   		bizAttribute.setValue(user.getUserId());
	   		attributeList.add(bizAttribute);
	   		
	   		ProcessHelper processHelper = ProcessHelper.instance();
			ProcessService bpmService = processHelper.getBPMService();
			String mobileBizUrl = (String) jsonObject.get("bizUrl");
			String[] flowInfoArray = mobileBizUrl.split("/");
			String processId = flowInfoArray[2];
			String processInstId = flowInfoArray[3];
			String activityCode = flowInfoArray[4];
			SubmitWorkItem processWorkItem = processHelper.createSubmitWorkItem(processId, processInstId, activityCode);
			if(StringUtil.isNullOrEmpty(attributeList.get(0).getCode())){
				attributeList = processWorkItem.getAttributeList();
			}
			processWorkItem.setUserCode(user.getUserCode());
			processWorkItem.getAttributeList().addAll(attributeList);
			bpmService.submitProcess(processWorkItem);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
}
